package com.itheima.priorityqueue;

import com.itheima.queue.Queue;

/**
 * 基于无序数组实现
 *
 * @FileName PriorityQueue1
 * @Description
 * @Author Sword
 * @date 2025-05-14
 **/
public class PriorityQueue1<E extends Priority> implements Queue<E> {

    Priority[] array;
    int size;

    public PriorityQueue1(int capacity) {
        array = new Priority[capacity];
    }

    // O(1)
    @Override
    public boolean offer(E valvue) {
        if (isFull()) {
            return false;
        }

        array[size++] = valvue;
        return true;
    }

    /**
     * 返回优先级最高的索引值
     *
     * @return
     */
    private int selectMax() {
        int Max = 0;
        for (int i = 1; i < size; i++) {
            if (array[i].priority() > array[Max].priority()) {
                Max = i;
            }
        }
        return Max;
    }

    //O(n)
    @Override
    public E poll() {
        if (isEmpty()) {
            return null;
        }

        int max = selectMax();
        E e = (E) array[max];
        remove(max);
        return e;
    }

    private void remove(int index) {
        //移动
        System.arraycopy(array, index + 1, array, index, size - 1 - index);
        array[--size] = null;   //help GC
    }

    @Override
    public E peek() {
        if (isEmpty()) {
            return null;
        }

        int max = selectMax();
        return (E) array[max];
    }

    @Override
    public boolean isEmpty() {
        return size == 0;
    }

    @Override
    public boolean isFull() {
        return size == array.length;
    }
}
